use lazy_static::lazy_static;
use std::collections::HashMap;
use std::sync::Arc;
use test_netplc::{do_cmd, plc::Plc, Connect, Seed};
use tokio::sync::Mutex;
use tracing::{instrument, warn};
use tracing_subscriber::prelude::*;
use warp::{hyper::body::Bytes, Filter};

#[instrument(skip_all, name = "main")]
#[tokio::main]
async fn main() {
    base::trace_warn!();

    lazy_static! {
        static ref SEED: Seed = Arc::new(Mutex::new(0));
        static ref CONNECT: Connect = {
            let mut m = HashMap::new();
            for i in 1..=100 {
                let k = format!("plc{:?}", i);
                m.insert(k, Arc::new(Mutex::new(Box::new(Plc::new()))));
            }

            m
        };
    }

    let md = "netplc";
    let body = base::body!();

    let post_three = warp::path(md)
        .and(warp::path::param())
        .and(warp::path::param())
        .and(body)
        .and_then(move |plc: String, cmd: String, data: Bytes| async {
            do_cmd(data, plc, cmd, &CONNECT, SEED.clone()).await
        });

    let post = warp::post().and(post_three).with(base::cors!());

    let get = warp::get().map(move || format!("\nserve: {}\n\n", md));
    let opt = base::opt!();

    let route = get.or(opt).or(post);

    warn!("listening on 0.0.0.0:9960");

    warp::serve(route).run(([0, 0, 0, 0], 9960)).await;
}
